package org.snake.nebulae.core.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@Slf4j
public class TaskExecutorFactory {

    /**
     * 创建一个任务执行管理器自己的后台线程 提供定时任务
     *
     * @param taskExecutorManager 任务执行管理器
     * @return 线程池
     */
    public static ThreadPoolTaskScheduler createPool(TaskExecutorManager taskExecutorManager) {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(1);
        threadPoolTaskScheduler
                .setErrorHandler(throwable ->
                        log.error("{} 线程致性错误 原因是: {}", Thread.currentThread().getClass(), throwable.getMessage()));
        threadPoolTaskScheduler.setThreadFactory(r -> {
            Thread thread = new Thread(r);
            thread.setName(taskExecutorManager.getClass().toString());
            return thread;
        });

        threadPoolTaskScheduler.setBeanName(taskExecutorManager.getClass().toString());
        threadPoolTaskScheduler.setThreadNamePrefix("tem");

        threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);

        threadPoolTaskScheduler.initialize();

        return threadPoolTaskScheduler;
    }

    /**
     * 根据TaskWrap来创建相关线程池
     *
     * @param taskWrap 任务包装
     * @return 线程池
     */
    public static ThreadPoolTaskScheduler createPool(TaskWrap taskWrap) {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(1);
        threadPoolTaskScheduler
                .setErrorHandler(throwable ->
                        log.error("{} 线程致性错误 原因是: {}", Thread.currentThread().getClass(), throwable.getMessage()));
        threadPoolTaskScheduler.setThreadFactory(r -> {
            Thread thread = new Thread(r);
            thread.setName(taskWrap.getKlass().toString());
            return thread;
        });

        threadPoolTaskScheduler.setBeanName(taskWrap.getKlass().toString());
        threadPoolTaskScheduler.setThreadNamePrefix("wrap");

        threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);

        //threadPoolTaskScheduler

        threadPoolTaskScheduler.initialize();

        return threadPoolTaskScheduler;
    }
}
